<template>
  <view class="searchGoods">
    <u-gap height="10" />
    <u-search
      ref="searchGoodsInput"
      v-model="value"
      show-action
      actionText="搜索"
      animation
      focus
      placeholder="请输入商品关键字"
      bgColor="#ffffff"
      @search="sendSearch"
      @custom="sendSearch"
    />
    <view class="searchGoods-history mt30">
      <view class="searchGoods-history-header">
        <text class="fs14 ml10">历史记录</text>
      </view>
      <view class="searchGoods-history-list flex">
        <u-tag
          v-for="(item, index) in search_historyRecord"
          :key="index"
          :text="item"
          plain
          plainFill
          color="#ea64a2"
          bgColor="#f1dce7"
          borderColor="#f1dce7"
          closable
          @close="historyListClose(index)"
          @click="sendTags(index)"
        />
      </view>
    </view>
  </view>
</template>

<script>
export default {
  name: "SearchGoods", // 搜索商品页
  options: { styleIsolation: "shared" }, // 父组件设置 options.styleIsolation 可穿透子组件，以及页面
  data() {
    return {
      search_historyRecord: [], // 搜索输入历史记录
      value: "",
    };
  },
  onShow() {
    // 获取历史记录
    this.search_historyRecord =
      uni.getStorageSync("search_historyRecord") || [];
    console.log("历史记录", this.search_historyRecord);
  },
  watch: {
    search_historyRecord: {
      handler(n) {
        this.maxHistoryListRemove();
      },
      deep: true,
    },
  },
  methods: {
    // 点击标签 跳转商品列表
    sendTags(index) {
      uni.navigateTo({
        url: `/pages/goodsList/goodsList?name=${this.search_historyRecord[index]}`,
        animationType: "pop-in",
        animationDuration: 200,
      });
      this.search_historyRecord.unshift(this.search_historyRecord.splice(index, 1)[0]) // 数组置顶
    },
    // 点击搜索 || 软键盘点击搜索触发
    sendSearch(value) {
      this.search_historyRecord.unshift(value);
      uni.navigateTo({
        url: `/pages/goodsList/goodsList?name=${value}`,
        animationType: "pop-in",
        animationDuration: 200,
      });
      // uni.setStorageSync('search_historyRecord', this.search_historyRecord)
    },
    // 删除单个历史记录
    historyListClose(idnex) {
      this.search_historyRecord.splice(idnex, 1);
      // uni.setStorageSync('search_historyRecord', this.search_historyRecord)
    },
    // 超过20条删除旧的
    maxHistoryListRemove() {
      if (this.search_historyRecord.length < 10) {
        return;
      }
      this.search_historyRecord.forEach((item, index) => {
        if (index > 9) {
          this.search_historyRecord.splice(index, 1);
        }
      });
      uni.setStorageSync("search_historyRecord", this.search_historyRecord);
    },
  },
};
</script>

<style lang="scss" scoped>
.searchGoods {
  padding: 20rpx 20rpx;
  &-history {
    &-list {
      /deep/ .u-tag {
        margin: 10rpx 20rpx;
        letter-spacing: 4rpx;
      }
    }
  }
}
</style>
